package com.eduask.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.eduask.dao.UserDao;
import com.eduask.model.Email;
import com.eduask.model.SeeEmail;
import com.eduask.model.User;

@Repository
public class UserDaoImpl implements UserDao{
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public Session getSession(){
		return sessionFactory.openSession();
	}
	
	

	@Override
	public boolean selectuser(User user) {
		Session s=getSession();
		SQLQuery sql=s.createSQLQuery("select * from user where username=? and password=?");
		sql.setString(0, user.getUsername());
		sql.setString(1, user.getPassword());
		if(sql.list().size()>0){
			s.close();
			System.out.println("我去数据库查过了 并关闭了事物");
			return true;
		}else{
			s.close();
			return false;
		}
		
	}



	@Override
	public List<Email> useremail(String username_email) {
		Session s=getSession();
		List<Email> el=new ArrayList();
		
		SQLQuery sql=s.createSQLQuery("select * from email where e_username=? ORDER BY e_second DESC");
		sql.setString(0, username_email);
		for(Object ob:sql.list()){
			Email e=new Email();
			Object[] ob1 = (Object[]) ob;
			e.setEtitle(String.valueOf(ob1[0]));
			e.setEcontent(String.valueOf(ob1[1]));
			e.setE_username(String.valueOf(ob1[2]));
			e.setE_time(String.valueOf(ob1[3]));
			e.setE_receive(String.valueOf(ob1[4]));
			e.setE_second(String.valueOf(ob1[5]));
			e.setEid(Integer.valueOf(String.valueOf(ob1[6])));
			el.add(e);
		}
		s.close();
		
		System.out.println(el);
		return el;
	}



	@Override
	public List<SeeEmail> seeEmail(int eid) {
		// TODO Auto-generated method stub
		Session s=getSession();
		List<SeeEmail> el=new ArrayList();
		SQLQuery sql=s.createSQLQuery("select a.*,e.truename as truename2 from (select econtent,e_username,e_receive,truename from email LEFT JOIN user on email.e_username = `user`.username where eid=?) a LEFT JOIN user e on a.e_receive = e.username");
		sql.setInteger(0, eid);
		SeeEmail se=new SeeEmail();
		for(Object ob:sql.list()){
			Object[] ob1 = (Object[]) ob;
			se.setSendEmail(String.valueOf(ob1[3]));
			se.setContent(String.valueOf(ob1[0]));
			se.setReceive(String.valueOf(ob1[4]));
		}
		el.add(se);
		s.close();
		return el;
	}

	

}
